<?php  
	session_start();
include_once '../pushing.php';

if ($pushTime == true) {
	if ($_SESSION['UserId'] != 3)
		header('Location: push.php');
}
	
	if(!isset($_SESSION['UserId']))
	{
		header('Location: login.php');
   		die();
	}
	
	require_once '../mysqlConnect.php'; //mysqli database connect
	include_once '../Functions/generateQuestions.php';
	
	$conn = GetConnection();
	$sql = "SELECT * FROM prescription_questions order by qnumber";
	$result = $conn->query($sql);
	$prescription_questions = array();
	
	while ($row = $result->fetch_assoc()) {
		$prescription_questions[] = $row;
	}
	
	//generate all question HTML
	$HTML = generateQuestions($prescription_questions);
	
	
function getPatientInfobyID($id)
{
	$conn = GetConnection();
	$sql = "SELECT * FROM Patient WHERE ID ='$id'";
	$value = $conn->query($sql);
	$rs = $value->fetch_assoc();
	return $rs;	
	$conn->close();
}

function getSectionInfobyID ($id)
{
	$conn = GetConnection();
	$sql = "SELECT * FROM Section S WHERE S.ID = '$id'";
	$value = $conn->query($sql);
	$rs = $value->fetch_assoc();
	return $rs;	
	$conn->close();
}


function uploadPrescription($patId, $medId, $dosage, $startdate, $enddate)	
{
	$conn = GetConnection();

	if ($enddate == "" || $enddate == null)
		$sql = "INSERT INTO prescription_records (patient_id, start_date, medication_id, dosage) VALUES ('$patId','$startdate', '$medId', '$dosage')";
	else	
		$sql = "INSERT INTO prescription_records (patient_id, start_date, end_date, medication_id, dosage) VALUES ('$patId','$startdate', '$enddate', '$medId', '$dosage')";	
	$conn->query($sql);
	
	if ($conn->error)
		return false;
	else 
		return true;
	$conn->close();
}

$SectionInfo = getSectionInfobyID (4); // retrieves all fields from "Section" table
$patientInfo = getPatientInfobyID($_REQUEST['PatId']);
$PATID = $_GET['PatId'];


if (isset($_REQUEST['isPostBack'])) {//if the user has reloaded the page using the submit button

	
	$ValidationErrors = array();

	//automated error checker
	foreach ($HTML as $key => $value) {
		
		if (isset($_POST[$value[0]['answerName']])) {
			
			$ans = $_POST[$value[0]['answerName']];
			
			switch($value[0]['type']) {
				
				case 1: //drop down menu
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 2://text input
					if ($ans == '' || $ans == null) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 3://date input
					if ($ans == '' || $ans == null) {
						//$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 4://medication drop down
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 5://test drop down
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
			}
		}
	}

	
	if (!(count($ValidationErrors) > 0)) {
		
		$upload = uploadPrescription($_GET['PatId'], $_POST[$HTML[0][0]['answerName']], $_POST[$HTML[1][0]['answerName']], $_POST[$HTML[2][0]['answerName']], $_POST[$HTML[3][0]['answerName']]);
		
		if ($upload == false) {
			echo '<script language="javascript" type="text/javascript">
			alert("Coult NOT Upload Prescription for Patient ' . $patientInfo['PatID'] . ': Database Query Error");
			redirect();
			function redirect(){
				window.location.href = "Add Prescription.php?PatId=' . $_GET['PatId'] . '";
			}
			</script>';
		} else {
			echo '<script language="javascript" type="text/javascript">
			alert("Prescription for Patient ' . $patientInfo['PatID'] . ' Successfully Added to Database");
			redirect();
			function redirect(){
				window.location.href = "Add Prescription.php?PatId=' . $_GET['PatId'] . '";
			}
			</script>';
		}
	}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Add Prescription</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
	<script src="../JavaScript/jQueryTabs/js/jquery-1.6.2.min.js" type="text/javascript"></script>
	<script src="../JavaScript/jQueryTabs/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
	<link rel="stylesheet" type="text/css" href="../JavaScript/jQueryTabs/css/custom-theme/jquery-ui-1.8.16.custom.css"/>
	<script type="text/javascript">
		$(document).ready(function() {
			//$("#Q51").hide();	

			<?php if (isset($ValidationErrors)) { 
					if (count($ValidationErrors) > 0 ) {
						foreach ($ValidationErrors as $key => $value) { ?>
							$("#<?php echo $value['textId'];?>").css('color', 'red');
						<?php } 
					}
				}?>
		});
	</script>
<link rel="stylesheet" type="text/css" href="../Styler.css"/>
</head>

<body>

 <div id="header">
 
    	<div class="pageTitleText">Add Prescription</div>
    	<div class="pageTitleText" style="font-size: 1em;">
	        <span class="pageTitleSub">Patient: <?php echo $patientInfo['PatID'];?></span>
	        <span class="pageTitleSub">Date Diagnosed: <?php echo $patientInfo['DateDiagnosed'];?></span>
        </div>
 </div>  
    
    
    <div id="mainMenu" style="height: 451px;">
    	<ul style="list-style: none outside none;">
	        
	        <li>
    			<a href="choosePatient.php?SID=4" style="font-weight: bold; color: #7C3709;">Choose New Patient</a>
    		</li>

	        <li>
	         	<a href="Add_ICD9.php?PatId=<?php echo $_GET['PatId'];?>">Patient ICD9</a>
	        </li>

	        <li>
	         	<a href="Add Prescription.php?PatId=<?php echo $_GET['PatId'];?>" style="font-weight: bold; color: #FB7D08;">Patient Prescription</a>
	        </li>
	        
	        <li>
	        	<a href="Physical Symptoms.php?PatId=<?php echo $_GET['PatId'];?>">Physical Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Neuropsychological Symptoms.php?PatId=<?php echo $_GET['PatId'];?>">Neuropsychological Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Psychological Test.php?PatId=<?php echo $_GET['PatId'];?>">Psychological Test</a> 
	        </li>
	        
	        <li>
	        	<a href="Diagnostic Test.php?PatId=<?php echo $_GET['PatId'];?>">Diagnostic Test</a>
	        </li>
	        
	        <li>
	        	<a href="viewPatient.php?PatId=<?php echo $_GET['PatId'];?>">View Patient Information</a>
	        </li>
	        
	        <li>
	         	<a href="Edit Patient.php?PatId=<?php echo $_GET['PatId'];?>">Edit Patient Information</a>
	        </li>
	        
	        <li>
	        	<a href="Save Information.php?PatId=<?php echo $_GET['PatId'];?>">Save Patient Information</a>
	        </li>
	        
	        <li style="border-bottom: 1px solid #FD9D45;">
	       	 	<del><!--<a href="query.php">-->Query<!--</a>--></del>
	        </li>
	        
	        <li>
	       	 	<a href="home.php">Home</a>
	        </li> 
	         
	        <li>
	       	 	<a href="logout.php">Logout</a>
	        </li>
        </ul>
    </div>  
   	   
    <?php if(isset($ValidationErrors)) { 

    	if (count($ValidationErrors) > 0) {?>
			
			<div class="noQueryResults">
			    <img src="../Images/error.png" style="float:left; margin: 5px 5px 5px 15px;"></img>
			    <p style="font-weight: bold; line-height: 1; margin: 5px 5px 5px 55px;">Error</p>
				<p style="line-height: 1; margin: 5px 5px 5px 55px;">		
		    	<?php if (count($ValidationErrors) > 1) { 
		    		echo 'Multiple Errors';
		    	} else { 
		    		echo 'Error';
		    	}?>
		    	</p>
			</div>
			
    <?php } }?>
    
        
        <div class="formContainer">
        	
	           <form name="addPatientForm" method="post" action="<?php echo $_SERVER["PHP_SELF"] . '?PatId=' . $_GET['PatId']; ?>">
		           <input type="hidden" name="isPostBack" value="true" />
		          
		           <div class="Questions" style="width: 630px; height: 230px;">
			            <div class="questionLeftColumn"> 
			                <?php 
			                $i = 0;
			                for ($i; $i < ceil(count($HTML)/2); $i++) {	
			                  	echo $HTML[$i][1];
			                } ?>
			            </div>
			           <div class="questionMiddleColumn">
			           		<?php for ($i; $i < count($HTML); $i++) {	
			                   	echo $HTML[$i][1];
			                } ?>
			           </div>
		           </div> 
		           
		          <input type="submit" value="Submit" class="loginButton" style="margin-top: 0px;"/>
	           </form>
	          
		</div>
   
   
</body>
</html>